import React, { ReactElement, useRef, useEffect, RefObject } from 'react'
import { Modal, Form, FormInstance, Input, message, Select } from 'antd'
import { addRequest, updateRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import _ from 'lodash'
import { RoleShcema } from '@src/components/schema/role'
import { AuthoritySchema } from '@src/components/schema/authority'

const { Item } = Form
const { Option } = Select

interface Props {
  visible: boolean
  hide: () => void
  data: RoleShcema | null
  desktops: AuthoritySchema[]
  refreshData: () => void
}

interface FormData {
  id?: string
  name?: string
  desktop?: string
}

async function submitHandle (d: FormData, desktops: AuthoritySchema[], refreshData: () => void, hide: () => void): Promise<void> {
  const desktopIds = desktops.map(li => li.id)
  let e: Error | null = null
  const data: { [k: string]: any } = {
    ...d
  }
  if (data.rules instanceof Array) {
    data.rules = data.rules.filter(li => !desktopIds.includes(li))
    data.rules.push(d.desktop)
  } else {
    data.rules = [d.desktop]
  }
  delete d.desktop
  const h = message.loading('提交中', 120)
  if (d.id === undefined) {
    const r = await awaitWrap(addRequest(data))
    e = r[0]
  } else {
    const r = await awaitWrap(updateRequest(data))
    e = r[0]
  }
  h()
  if (e === null) {
    message.success(d.id === undefined ? '添加成功' : '更新成功').then(null, null)
    refreshData()
    hide()
  }
}

function initData (data: RoleShcema, formRef: RefObject<FormInstance>, desktops: AuthoritySchema[]): void {
  const o: { [k: string]: any } = { ..._.cloneDeep(data) }
  const keys = Object.keys(o)
  keys.forEach(k => {
    if (o[k] === null) {
      o[k] = undefined
    }
  })
  const desktopIds = desktops.map(li => li.id)
  if (o.rules instanceof Array) {
    for (let i = 0; i < o.rules.length; i++) {
      if (desktopIds.includes(o.rules[i])) {
        o.desktop = o.rules[i]
        break
      }
    }
  }
  formRef.current?.setFieldsValue(o)
}

function Main ({ visible, hide, data, desktops, refreshData }: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  useEffect(() => {
    if (visible) {
      if (data === null) {
        ref.current?.resetFields()
      } else {
        initData(data, ref, desktops)
      }
    } else {
      ref.current?.resetFields()
    }
  }, [visible])
  return (
    <Modal title={data !== null ? '编辑角色' : '新增角色'} visible={visible} onOk={() => ref.current?.submit()} maskClosable={false} onCancel={() => hide()}>
      <Form ref={ref} labelCol={{ flex: '88px' }} initialValues={{ gender: '男' }} onFinish={async d => await submitHandle(d, desktops, refreshData, hide)}>
        <Item name='id' noStyle><span /></Item>
        <Item name='name' noStyle><span /></Item>
        <Item name='rules' noStyle><span /></Item>
        <Item label='名称' name='name' rules={[{ required: true, message: '姓名不能为空' }]}>
          <Input placeholder='请输入' />
        </Item>
        <Item label='桌面' name='desktop' rules={[{ required: true, message: '桌面不能为空' }]}>
          <Select placeholder='请选择'>
            {
              desktops.map(li => {
                return <Option value={li.id} key={li.id}>{li.name}</Option>
              })
            }
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
